package com.nuanshui.heatedloan.baseservice.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;

import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.heatedloan.baseservice.constant.MediaBizType;
import com.nuanshui.heatedloan.baseservice.constant.MediaType;
import com.nuanshui.heatedloan.baseservice.dal.mapper.ArticleMapper;
import com.nuanshui.heatedloan.baseservice.facade.*;
import com.nuanshui.heatedloan.baseservice.form.ArticleForm;
import com.nuanshui.heatedloan.baseservice.form.MediaForm;
import com.nuanshui.heatedloan.baseservice.model.ArticleType;
import com.nuanshui.heatedloan.baseservice.vo.ArticleTypeVO;
import com.nuanshui.heatedloan.baseservice.vo.ArticleVO;
import com.nuanshui.heatedloan.baseservice.vo.MediaVO;
import com.nuanshui.heatedloan.constant.GlobalParam;
import com.nuanshui.heatedloan.constant.ServiceConstant;
import com.nuanshui.heatedloan.constant.TransactionManagerType;
import com.nuanshui.heatedloan.dubbo.extension.cache.manager.DubboCacheManager;
import com.nuanshui.heatedloan.middleware.rabbitmq.RabbitmqMessageSender;
import com.nuanshui.heatedloan.model.Image;
import com.nuanshui.heatedloan.module.model.AdvertisementBizType;
import com.nuanshui.heatedloan.pageable.Pager;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(ServiceConstant.ARTICLESERVICE)
@Transactional(readOnly = true, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ImageService imageService;

    @Autowired
    private Image2MediaImageConvert image2MediaImageConvert;


    @Autowired
    private AdvertisementService advertisementService;

    @Autowired
    private MediaService mediaService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    public RabbitmqMessageSender rabbitmqMessageSender; //rabbit的生产者

    @Autowired
    private DubboCacheManager dubboCacheManager;

    @Override
    public Pager<ArticleVO> loadArticle(Pager<ArticleVO> pager,ArticleForm articleForm) {
        List<ArticleVO> list= articleMapper.loadArticle(pager,articleForm);
        pager.setData(list);
        return pager;
    }

    public List<ArticleType> getAllArticleType() {
        return articleMapper.getArticleType(new ArticleType());
    }

    public ArticleType loadArticleType(String id) {
        ArticleType item = new ArticleType();
        item.setId(id);
        List<ArticleType> list = articleMapper.getArticleType(item);

        if (list.size() > 0)
            return list.get(0);

        return null;
    }

    public List<ArticleType> getArticleType(ArticleType articleType) {
        return articleMapper.getArticleType(articleType);
    }

    @Transactional(readOnly = false, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
    public void saveArticleType(ArticleType articleType) {
        articleMapper.saveArticleType(articleType);
    }

    @Transactional(readOnly = false, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
    public void updateArticleType(ArticleType articleType) {
        //先将旧资讯动态删除(存档)
        //articleMapper.deleteArticleTypeById(ArticleType);
        //新增新资讯动态
        //articleMapper.saveArticleType(ArticleType);
        articleMapper.updateArticleType(articleType);
    }

    @Transactional(readOnly = false, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
    public void deleteArticleTypeById(String id) {
        articleMapper.deleteArticleTypeById(id);
    }

    /**
     * 添加资讯动态
     *
     * @param form
     */
    @Override
    @Transactional(readOnly = false, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
    public void save(ArticleForm form) {

        articleMapper.save(form);
        saveArticleMedias(form);
    }

    /**
     * 保存文章的medias
     *
     * @param form
     * @author Gonzo
     * @date 2017年1月3日下午5:29:41
     * @since 1.0.0
     */
    private void saveArticleMedias(ArticleForm form) {
        //保存封面图

        if (SysStringUtils.isNotEmpty(form.getCoverList())) {
            List<MediaForm> coverMediForms = JSON.parseArray(form.getCoverList(), MediaForm.class);
            int orderNum = 0;
            for (MediaForm mediaForm : coverMediForms) {
                Image image = image2MediaImageConvert.mediaFromImage2Image(mediaForm);
                imageService.insert(image);
                advertisementService.saveAdvertisementByImage(image, form.getId(), AdvertisementBizType.ADVERTISEMENT_MUSEUM_ARTICLE_BANNER, orderNum);
                orderNum++;
            }
        }

        if (SysStringUtils.isNotEmpty(form.getContent())) {
            MediaForm item=new MediaForm();
            item.setType(MediaType.HTML);
            item.setBizType(MediaBizType.ARTICLE);
            item.setBizId(form.getId());
            item.setHtmlText(form.getContent());
            //保存medias
            mediaService.save(item);
        }
    }

    @Override
    @Transactional(readOnly = false, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
    public void update(ArticleForm form) {
        //先将原有的置为存档。
        //advertisementService.deleteAdvertisement(form.getId(), AdvertisementBizType.ADVERTISEMENT_MUSEUM_ARTICLE_BANNER);
        //mediaService.deleteMedia(form.getId(), MediaBizType.ARTICLE);
        //然后调用更新的方法
        articleMapper.update(form);

        MediaVO media=mediaService.findFirstMedia(form.getId(), MediaBizType.ARTICLE);

        if (media!=null && SysStringUtils.isNotEmpty(form.getContent())) {
            media.setHtmlText(form.getContent());
            //更新medias
            mediaService.updateMedia(media);
        }
    }

    @Override
    public ArticleVO loadVo(String id) {
        ArticleVO item=articleMapper.loadVo(id);

        if(item!=null)
        {
            setArticleContent(item);
        }

        return item;
    }

    private void setArticleContent(ArticleVO item)
    {
        if(item!=null)
        {
            List<MediaVO> medias=mediaService.listMedia(item.getId(), MediaBizType.ARTICLE);

            if(medias!=null)
            {
                MediaVO htmlMedia=CollectionUtils.find(medias, new Predicate<MediaVO>() {
                    public boolean evaluate(MediaVO object) {
                        return object.getType()==MediaType.HTML;
                    }
                });

                if(htmlMedia!=null)
                {
                    item.setContent(htmlMedia.getHtmlText());
                } else
                {
                    item.setMedias(medias);
                }
            }

            //item.setCoverList(advertisementService.findByBizTypeAndBizId(AdvertisementBizType.ADVERTISEMENT_MUSEUM_ARTICLE_BANNER,item.getId()));

        }
    }

    @Override
    public List<ArticleTypeVO> getCatArticleList(List<String> catIds)
    {
        List<ArticleTypeVO> typeList=articleMapper.getCatArticleList(catIds);

        Map<String,ArticleTypeVO> map=new HashMap<String,ArticleTypeVO>();
        //resort
        for (ArticleTypeVO item : typeList) {

            map.put(item.getId(),item);
        }
        typeList.clear();
        for (String item : catIds) {

            typeList.add(map.get(item));
        }

        for (ArticleTypeVO item : typeList) {

            Pager<ArticleVO> articlePager=getArticleListByType(item.getId(),new Pager<ArticleVO>(1,20));

            if(articlePager!=null && articlePager.getData()!=null)
            {
                item.setArticleList(articlePager.getData());
            }
        }

        return typeList;
    }

    @Override
    public Pager<ArticleVO> getArticleListByType(String typeId, Pager<ArticleVO> pager) {
        List<ArticleVO> list = articleMapper.getArticleListByType(typeId, pager);
        pager.setData(list);
        return pager;
    }

    @Override
    @Transactional(readOnly = false, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
    public void delete(String articleId) {
        articleMapper.delete(articleId);
        mediaService.deleteMedia(articleId,MediaBizType.ARTICLE);
    }

    @Override
    @Transactional(readOnly = false, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
    public void changeStatus(Integer status, String articleId) {
        articleMapper.changeStatus(status, articleId);
    }


    @Override
    public int countByArticleTypeId(String articleTypeId) {
        return articleMapper.countByArticleTypeId(articleTypeId);
    }


    @Override
    @Transactional(readOnly = false, value = TransactionManagerType.BASE_SERVICE_TRANSACTION_MANAGER)
    public void createArticleFromBackground(ArticleForm ArticleForm) {
        articleMapper.save(ArticleForm);

        Image image = imageService.load(ArticleForm.getCoverImgId());

        advertisementService.saveAdvertisementByImage(image, ArticleForm.getId(), AdvertisementBizType.ADVERTISEMENT_MUSEUM_ARTICLE_BANNER, 0);

        MediaForm form = new MediaForm();
        form.setHtmlText(ArticleForm.getMediaHtml());
        form.setType(MediaType.HTML);
        List<MediaForm> formList = Lists.newArrayList();
        formList.add(form);
        mediaService.save(JSON.toJSONString(formList), MediaBizType.ARTICLE, ArticleForm.getId());

    }

    @Override
    public ArticleVO loadArticleByAlias(String alias) {
        ArticleVO item=articleMapper.loadArticleByAlias(alias);

        if(item!=null)
        {
            setArticleContent(item);
        }
        return item;
    }
}
